<template>
  <div>
        <el-tree
          :data="treeData"
          show-checkbox
          node-key="id"
          ref="tree"
          highlight-current
          default-expand-all
          :default-checked-keys="defaultCheckList"
          :render-content="renderContent"
          :props="defaultProps"
           @check-change="handleCheckChange"
          >
        </el-tree>
        <!-- <el-button @click="setCheckedKeys">node</el-button> -->
  </div>
</template>



<script>
  export default{
    props:["treeData"],
    data(){
      return{
        defaultProps: {
          children: 'children',
          label: 'text'
        },
        ids:[],
        defaultCheckList:[],//默认选中
      }
    },
    mounted() {
    },
    watch:{
      treeData(){
        this.traverseNode(this.treeData)
        setTimeout(()=>{
          this.setCheckedKeys()
        },300)
      }
    },
    methods:{
      // 遍历节点 取出以选数据对应的所选id
      traverseNode(array){
        let arr = []
        let arrFilter = []
        array.forEach(el=>{
          if(el.checked){
            arr.push(el.id) //所有后台返回选中得id
          }
          if(el.checked && el.children.length){
             arrFilter.push(el.id)//所有有子集菜单得 父级id
          }
          if(el.children){
            arr.push(...this.traverseNode(el.children))
          }
        })

        //默认选中得id （过滤掉父级id，避免全选）
        // this.defaultCheckList = arr
        this.defaultCheckList = arr.filter(function(n) {
                                    return arrFilter.indexOf(n) == -1
                                })
        //过滤顶级节点 
        this.defaultCheckList = this.defaultCheckList.filter(el=>el != '-1')
        console.log(this.defaultCheckList,1111)
        return arr
      },
      // 选择的id数组
      getCheckedNodes() {
        this.ids = []
        // console.log(this.$refs.tree.getCheckedNodes());
        this.$refs.tree.getCheckedNodes().forEach(el=>{
          if(el.children){
            this.ids.push(el.id)
            // console.log(this.ids)
          }
        })
      },
      handleCheckChange(){
        this.getCheckedNodes()
        this.$emit('handleChooseNode',this.ids)
      },
      // 选择默认值
      setCheckedKeys() {
        this.$refs.tree.setCheckedKeys(this.defaultCheckList)
      },
      renderContent(h, { node, data, store }){
        return (
            <span>
              <i class='el-icon-document'></i>
              <span>{node.label}</span>
            </span>
          )
      }
    }
  }
</script>
